package com.meisupic.copyright.support.security;

import com.alibaba.fastjson.JSON;
import com.meisupic.copyright.domain.bo.SysUser;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * @Author lanjian
 * @Date 2018/2/2 下午2:23
 */
@Component
public class CustomAuthenticationSuccessHandler extends
    SavedRequestAwareAuthenticationSuccessHandler {

  protected final Log logger = LogFactory.getLog(this.getClass());

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request,
      HttpServletResponse response, Authentication authentication)
      throws ServletException, IOException {
    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {

      SysUser user = (SysUser) authentication.getPrincipal();
      user.setPassword(null);
      user.setSalt(null);

      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);    //json
      response.setStatus(HttpStatus.OK.value());

      final PrintWriter out = response.getWriter();
      response.setCharacterEncoding("UTF-8");
      out.print(JSON.toJSONString(user));
      out.flush();
    } else {
      super.onAuthenticationSuccess(request, response, authentication);
    }

  }


}